<template>
	<view class="container">
		<image class="banner" src="/static/svg/practice.svg" mode="widthFix"></image>
		<uni-transition mode-class="fade" :show="!!currentQuestion">
			<uni-card v-if="currentQuestion" :is-shadow="true" margin="20px 0">
				<view class="progress">
					<text class="progress-text">第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题</text>
					<view class="progress-bar">
						<view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
					</view>
				</view>
				<view class="question-content">
					<text class="question-text">{{ currentQuestion.question }}</text>
				</view>
				<view class="options-list">
					<view 
						v-for="(option, index) in currentQuestion.options" 
						:key="index"
						class="option-item"
						:class="{
							'selected': selectedAnswer === option.optionKey,
							'correct': showAnswer && option.optionKey === currentQuestion.answer,
							'wrong': showAnswer && selectedAnswer === option.optionKey && selectedAnswer !== currentQuestion.answer
						}"
						@click="selectOption(option.optionKey)"
					>
						<text class="option-label">{{ option.optionKey }}.</text>
						<text class="option-text">{{ option.optionValue }}</text>
						<view v-if="showAnswer && option.optionKey === currentQuestion.answer" class="correct-mark">✓</view>
						<view v-if="showAnswer && selectedAnswer === option.optionKey && selectedAnswer !== currentQuestion.answer" class="wrong-mark">✗</view>
					</view>
				</view>
				<view v-if="showAnswer" class="answer-section">
					<view class="answer-result" :class="isCorrect ? 'correct-result' : 'wrong-result'">
						<text>{{ isCorrect ? '回答正确！' : '回答错误！' }}</text>
					</view>
					<view class="explanation">
						<text class="explanation-title">解析：</text>
						<text class="explanation-text">{{ currentQuestion.explanation || '暂无解析' }}</text>
					</view>
				</view>
			</uni-card>
		</uni-transition>
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		<view v-if="!loading && questions.length === 0" class="empty">
			<text>暂无题目</text>
		</view>
		<view v-if="questions.length > 0" class="action-buttons">
			<button 
				class="btn btn-default" 
				:disabled="currentIndex === 0"
				@tap="prevQuestion"
			>
				上一题
			</button>
			<button 
				class="btn btn-primary" 
				:disabled="currentIndex === questions.length - 1"
				@tap="nextQuestion"
			>
				下一题
			</button>
			<button 
				class="btn btn-primary" 
				@tap="submitResult"
			>
				交卷
			</button>
		</view>
		<uni-popup ref="resultPopup" type="center">
			<view class="result-popup">
				<text class="result-title">本次成绩</text>
				<text class="result-score">{{ correctCount }} / {{ questions.length }}</text>
				<view class="result-actions">
					<button class="btn btn-primary" @tap="restart">再来一次</button>
					<button class="btn btn-default" @tap="goWrong">去错题本</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { get, post } from '@/utils/api.js'

export default {
	data() {
		return {
			questions: [], // 题目列表
			currentIndex: 0, // 当前题目索引
			selectedAnswer: '', // 选中的答案
			showAnswer: false, // 是否显示答案
			isCorrect: false, // 是否正确
			loading: false,
			answers: [],
			correctCount: 0
		}
	},
	computed: {
		currentQuestion() {
			return this.questions[this.currentIndex] || null
		},
		progressPercent() {
			if (!this.questions.length) return 0
			return Math.round(((this.currentIndex + 1) / this.questions.length) * 100)
		}
	},
	onLoad() {
		this.loadQuestions()
	},
	methods: {
		// 加载题目列表
		async loadQuestions() {
			this.loading = true
			try {
				const data = await get('/practice/questions')
				this.questions = data || []
				if (this.questions.length > 0) {
					this.resetQuestion()
				}
			} catch (error) {
				console.error('加载题目失败:', error)
			} finally {
				this.loading = false
			}
		},
		
		// 选择选项
		async selectOption(value) {
			if (!this.showAnswer && this.currentQuestion) {
				this.selectedAnswer = value
				console.log('选择答案:', value)
				console.log('当前题目:', this.currentQuestion)
				console.log('题目解析:', this.currentQuestion.explanation)
				
				// 立即显示答案和解析
				const isCorrect = value === this.currentQuestion.answer
				this.isCorrect = isCorrect
				this.showAnswer = true
				
				console.log('显示答案:', this.showAnswer)
				console.log('是否正确:', this.isCorrect)
				
				// 提交答题记录到后端
				try {
					console.log('提交答题记录:', {
						questionId: this.currentQuestion.id,
						interviewQuestionId: this.currentQuestion.interviewQuestionId,
						userAnswer: value,
						isCorrect: isCorrect
					})
					await post('/practice/record', {
						questionId: this.currentQuestion.id,
						interviewQuestionId: this.currentQuestion.interviewQuestionId,
						userAnswer: value,
						isCorrect: isCorrect
					})
					console.log('提交成功')
				} catch (error) {
					console.error('提交答题记录失败:', error)
					// 即使提交失败，也显示答案
				}

				const idx = this.answers.findIndex(a => a.id === this.currentQuestion.id)
				const record = { id: this.currentQuestion.id, userAnswer: value, isCorrect }
				if (idx >= 0) {
					this.answers.splice(idx, 1, record)
				} else {
					this.answers.push(record)
				}
			}
		},
		
		// 上一题
		prevQuestion() {
			if (this.currentIndex > 0) {
				this.currentIndex--
				this.resetQuestion()
			}
		},
		
		// 下一题
		nextQuestion() {
			if (this.currentIndex < this.questions.length - 1) {
				this.currentIndex++
				this.resetQuestion()
			}
		},

		submitResult() {
			this.correctCount = this.answers.filter(a => a.isCorrect).length
			try { uni.setStorageSync('practice_stats', { total: this.answers.length, correct: this.correctCount }) } catch(e) {}
			this.$refs.resultPopup.open()
		},

		restart() {
			this.currentIndex = 0
			this.answers = []
			this.resetQuestion()
			this.$refs.resultPopup.close()
		},

		goWrong() {
			this.$refs.resultPopup.close()
			uni.switchTab({ url: '/pages/wrong-questions/index' })
		},
		
		// 重置题目状态
		resetQuestion() {
			this.selectedAnswer = ''
			this.showAnswer = false
			this.isCorrect = false
		}
	}
}
</script>

<style lang="scss" scoped>
@import '@/styles/theme.scss';
.container {
	min-height: 100vh;
	background-color: #F9FAFB;
	padding-bottom: 100px;
}

.progress {
	padding: 10px 0;
	border-bottom: 1px solid #eee;
	margin-bottom: 20px;
}

.progress-text {
	font-size: 14px;
	color: #333;
}

.question-content {
	margin-bottom: 20px;
}

.question-text {
	font-size: 16px;
	line-height: 1.6;
	color: #333;
}

.options-list {
	margin-top: 20px;
}

.option-item {
	display: flex;
	align-items: flex-start;
	padding: 12px;
	margin-bottom: 10px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	background-color: #fff;
	position: relative;
	transition: all 0.3s;
}

.option-item.selected {
	border-color: #FF7F50;
	background-color: #fff3ee;
}

.option-item.correct {
	border-color: #4cd964;
	background-color: #f0fff4;
}

.option-item.wrong {
	border-color: #ff3b30;
	background-color: #fff5f5;
}

.option-label {
	font-weight: bold;
	margin-right: 8px;
	color: #333;
}

.option-text {
	flex: 1;
	font-size: 15px;
	line-height: 1.5;
	color: #333;
}

.correct-mark {
	position: absolute;
	right: 12px;
	top: 50%;
	transform: translateY(-50%);
	color: #4cd964;
	font-size: 20px;
	font-weight: bold;
}

.wrong-mark {
	position: absolute;
	right: 12px;
	top: 50%;
	transform: translateY(-50%);
	color: #ff3b30;
	font-size: 20px;
	font-weight: bold;
}

.answer-section {
	margin-top: 20px;
	padding-top: 20px;
	border-top: 1px solid #eee;
}

.answer-result {
	padding: 12px;
	border-radius: 8px;
	margin-bottom: 15px;
	text-align: center;
	font-size: 16px;
	font-weight: bold;
}

.correct-result {
	background-color: #f0fff4;
	color: #4cd964;
}

.wrong-result {
	background-color: #fff5f5;
	color: #ff3b30;
}

.explanation {
	margin-top: 15px;
}

.explanation-title {
	font-size: 15px;
	font-weight: bold;
	color: #333;
	margin-bottom: 8px;
	display: block;
}

.explanation-text {
	font-size: 14px;
	line-height: 1.6;
	color: #666;
	display: block;
}

.loading, .empty {
	text-align: center;
	padding: 40px 20px;
	color: #999;
}

.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-around;
	padding: 15px;
	background-color: #fff;
	border-top: 1px solid #eee;
	box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-buttons .btn {
	flex: 1;
	margin: 0 5px;
	padding: 12px 20px;
	border-radius: 8px;
	font-size: 16px;
	border: none;
	cursor: pointer;
}

.action-buttons .btn-default { }

.action-buttons .btn-default:disabled {
	background-color: #e0e0e0;
	color: #999;
	opacity: 0.6;
}

.action-buttons .btn-primary { }

.action-buttons .btn-primary:disabled {
	color: #fff;
	opacity: 0.6;
}

.action-buttons .btn:not(:disabled):active {
	opacity: 0.8;
}

.result-popup {
	width: 600rpx;
	padding: 30rpx;
	background-color: #ffffff;
	border-radius: 24rpx;
}
.result-title {
	font-size: 18px;
	color: #333;
	text-align: center;
	margin-bottom: 12px;
}
.result-score {
	font-size: 24px;
	color: #FF7F50;
	text-align: center;
	font-weight: 600;
	margin-bottom: 20px;
}
.result-actions {
	display: flex;
	gap: 12px;
}
</style>
